//
//  ToviewAddressViewController.m
//  何五路
//
//  Created by _ADY on 15/7/2.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "ToviewAddressViewController.h"

@interface ToviewAddressViewController ()

@end
static LoadingView *loading = nil;
#define AddAddHight 40
@implementation ToviewAddressViewController
@synthesize dic,mTableView;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"修改" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)];
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenMySize.size.width, screenMySize.size.height-60) style:UITableViewStyleGrouped];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.sectionHeaderHeight = 0.0;
    mTableView.sectionFooterHeight = 0.0;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mTableView];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
    [mTableView setTableFooterView:v];
    
    bgNameArray = [NSArray arrayWithObjects:@"收货人姓名",@"手机号码",@"电话号码",@"邮政编码",@"所在地区",@"街道",@"详细地址", nil];
    
    self.view.backgroundColor =bgColor;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(treatedATask) name:KAddressModify object:nil];
    
}
-(void)treatedATask
{
    [[NSNotificationCenter defaultCenter] postNotificationName:KAddressUpdate object:self];
    
    NSMutableDictionary *postDic1 = [[NSMutableDictionary alloc] init];
    
    [postDic1 setObject:[dic objectForKey:@"Id"] forKey:@"addressId"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *myArray = [SendService AddressGet:postDic1];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"重新当前ID获取收货地址 %@",myArray);
            dic =[[myArray objectForKey:@"Entity"] objectForKey:@"Address"];
            [mTableView reloadData];
        });
    });
    
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!dic) {
        self.title = @"收货地址";
        return;
    }
    if (![[NSString stringWithFormat:@"%@",[dic objectForKey:@"IsDefaultShippingAddress"]] isEqualToString:@"1"])
    {
        [self ToViewBarView];
        self.title = @"收货地址";
    }
    else
        self.title = @"默认收货地址";
}
#pragma mark 修改
-(void)rightAction
{
    ModifyAddressViewController *details = [[ModifyAddressViewController alloc] init];
    details.hidesBottomBarWhenPushed = YES;
    details.addDictionary = dic;
    [self.navigationController pushViewController:details animated:YES];
}

#pragma mark 设成默认收货地址
-(void)settlementAction
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定默认收货地址?"  delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
    alert.tag = 102;
    [alert show];
}
-(void)ToViewBarView
{
    UIView *barView = [[UIView alloc] initWithFrame:CGRectMake(0, screenMySize.size.height-60, screenMySize.size.width, 60)];
    barView.backgroundColor = [UIColor colorWithWhite:0 alpha:.8];
    [self.view addSubview:barView];
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [addButton setFrame:CGRectMake(0, 0, screenMySize.size.width, barView.frame.size.height)];
    [addButton setBackgroundColor:[UIColor colorWithRed:238/255.0 green:84/255.0 blue:84/255.0 alpha:1]];
    [addButton setTitle:@"设成默认收货地址" forState:UIControlStateNormal];
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(settlementAction) forControlEvents:UIControlEventTouchUpInside];
    [barView addSubview:addButton];
    
}


#pragma mark -
#pragma mark Table View DataSource

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
        return 0.001;
    return 10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
        return 7;
    return 1;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return AddAddHight;
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"AddressAddCell";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        aTableView.showsVerticalScrollIndicator = NO;
        //        cell.tintColor = [UIColor colorWithRed:243/255.0 green:125/255.0 blue:125/255.0 alpha:1];//勾选颜色
    }
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    aTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    cell.textLabel.textAlignment = 0;
    cell.detailTextLabel.textAlignment = 0;
    if (indexPath.section == 0)
    {
        cell.textLabel.text = [bgNameArray objectAtIndex:indexPath.row];
        cell.textLabel.textColor = [UIColor grayColor];
        cell.detailTextLabel.textColor = [UIColor blackColor];
        NSString *detailString = nil;
        if (indexPath.row == 0) {
            detailString = [NSString stringWithFormat:@"%@",[dic objectForKey:@"Name"]];
        }
        else if (indexPath.row == 1) {
            detailString = [NSString stringWithFormat:@"%@",[dic objectForKey:@"CellphoneNumber"]];
        }
        else if (indexPath.row == 2) {
            detailString = [NSString stringWithFormat:@"%@",[dic objectForKey:@"PhoneNumber"]];
        }
        else if (indexPath.row == 3) {
            detailString = [NSString stringWithFormat:@"%@",[dic objectForKey:@"ZipPostalCode"]];
        }
        else if (indexPath.row == 4) {
            detailString = [NSString stringWithFormat:@"%@%@%@",[dic objectForKey:@"StateProvinceName"],[dic objectForKey:@"CityName"],[dic objectForKey:@"DistrictName"]];
        }
        else if (indexPath.row == 5) {
            detailString = [NSString stringWithFormat:@"%@",[dic objectForKey:@"StreetName"]];
        }
        else if (indexPath.row == 6) {
            detailString = [NSString stringWithFormat:@"%@",[dic objectForKey:@"Address1"]];
        }
        detailString = [detailString stringByReplacingOccurrencesOfString:@"<null>" withString:@""];
        cell.detailTextLabel.text = detailString;
    }
    else
    {
        cell.textLabel.text = @"删除收货地址";
        cell.textLabel.textColor = [UIColor redColor];
    }

    
    // Configure the cell...
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section == 1)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定删除收货地址?"  delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        alert.tag = 100;
        [alert show];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100)
    {
        if (buttonIndex == 1)
        {
            loading = [[LoadingView alloc] initWithFrame:self.view.frame];
            [self.view addSubview:loading];
            
            NSMutableDictionary *postDic1 = [[NSMutableDictionary alloc] init];

            [postDic1 setObject:[dic objectForKey:@"Id"] forKey:@"addressId"];
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSDictionary *myArray = [SendService AddressDelete:postDic1];
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"删除收货地址 %@",myArray);
                    if ([[NSString stringWithFormat:@"%@",[myArray objectForKey:@"Result"]] isEqualToString:@"success"])
                    {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[myArray objectForKey:@"Message"]  delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        alert.tag = 101;
                        [alert show];
                    }
                    else
                        [SendService alerViewMessage:[myArray objectForKey:@"Message"]];
                    [loading closeLoading];
                });
            });
        }
    }
    else if (alertView.tag == 101)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:KAddressUpdate object:self];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else if (alertView.tag == 102)
    {
        if (buttonIndex == 1)
        {
            loading = [[LoadingView alloc] initWithFrame:self.view.frame];
            [self.view addSubview:loading];
            NSMutableDictionary *postDic1 = [[NSMutableDictionary alloc] init];
            
            [postDic1 setObject:[dic objectForKey:@"Id"] forKey:@"addressId"];
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSDictionary *myArray = [SendService SelectShippingAddress:postDic1];
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"设成默认收货地址 %@",myArray);
                    if ([[NSString stringWithFormat:@"%@",[myArray objectForKey:@"Result"]] isEqualToString:@"success"])
                    {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[myArray objectForKey:@"Message"]  delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        alert.tag = 101;
                        [alert show];
                    }
                    else
                        [SendService alerViewMessage:[myArray objectForKey:@"Message"]];
                     [loading closeLoading];
                });
            });
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
